// 蓝牙连接类
class BlueToothUtil {
    constructor(disCallback) {
        this.device = null;
        this.disCallback = disCallback;
        this.onDisconnected = this.onDisconnected.bind(this);
    }

    async request() {
        let options = {
            "filters": [{
                "namePrefix": "NBH",
                // "namePrefix": "真我",
            }],
            "optionalServices": [0xFFF0]
        };
        this.device = await navigator.bluetooth.requestDevice(options);
        if (!this.device) {
            throw "No device selected";
        }
        this.device.addEventListener('gattserverdisconnected', this.onDisconnected);
    }

    async connect() {
        if (!this.device) {
            return Promise.reject('Device is not connected.');
        }
        return await this.device.gatt.connect();
    }

    async readOrder() {
        const service = await this.device.gatt.getPrimaryService(0xFFF0);
        const characteristic = await service.getCharacteristic(0xFFF1);
        await characteristic.readValue();
    }

    async writeOrder(data) {
        const service = await this.device.gatt.getPrimaryService(0xFFF0);
        const characteristic = await service.getCharacteristic(0xFFF2);
        await characteristic.writeValue(data);
    }

    async startOrderNotifications(listener) {
        const service = await this.device.gatt.getPrimaryService(0xFFF0);
        const characteristic = await service.getCharacteristic(0xFFF1);
        await characteristic.startNotifications();
        characteristic.addEventListener('characteristicvaluechanged', listener);
    }

    async stopOrderNotifications(listener) {
        const service = await this.device.gatt.getPrimaryService(0xFFF0);
        const characteristic = await service.getCharacteristic(0xFFF1);
        await characteristic.stopNotifications();
        characteristic.removeEventListener('characteristicvaluechanged', listener);
    }

    disconnect() {
        if (!this.device) {
            return Promise.reject('Device is not connected.');
        }
        return this.device.gatt.disconnect();
    }

    onDisconnected() {
        if (this.disCallback) {
            this.disCallback();
        }
        console.log('Device is disconnected.');
    }
}